package com.example.ercmssystem2.controller;

import com.example.ercmssystem2.entity.User;
import com.example.ercmssystem2.service.UserService;
import com.example.ercmssystem2.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class ApiAuthController {

    private static final Logger logger = LoggerFactory.getLogger(ApiAuthController.class);

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest) {
        try {
            String username = loginRequest.get("username");
            String password = loginRequest.get("password");

            // 验证输入参数
            if (username == null || password == null || username.trim().isEmpty() || password.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "用户名和密码不能为空"
                ));
            }

            // 先检查用户是否存在
            User user = userService.findByUsername(username.trim());
            if (user == null) {
                logger.warn("登录失败：用户不存在 - {}", username);
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "用户名或密码错误"
                ));
            }

            if (!user.getEnabled()) {
                logger.warn("登录失败：用户账户已被禁用 - {}", username);
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "用户账户已被禁用"
                ));
            }

            // 验证用户凭据
            try {
                Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username.trim(), password)
                );

                if (authentication.isAuthenticated()) {
                    // 生成JWT token
                    String token = jwtUtil.generateToken(username.trim(), user.getRole());
                    
                    logger.info("用户登录成功: {}", username);
                    
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("message", "登录成功");
                    response.put("token", token);
                    response.put("user", Map.of(
                        "id", user.getId(),
                        "username", user.getUsername(),
                        "realName", user.getRealName(),
                        "role", user.getRole(),
                        "departmentId", user.getDepartmentId()
                    ));
                    
                    return ResponseEntity.ok(response);
                } else {
                    logger.warn("登录失败：认证失败 - {}", username);
                    return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "用户名或密码错误"
                    ));
                }
            } catch (Exception e) {
                logger.warn("登录失败：认证异常 - {} - {}", username, e.getMessage());
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "用户名或密码错误"
                ));
            }
        } catch (Exception e) {
            logger.error("登录处理异常: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "登录失败: " + e.getMessage()
            ));
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Map<String, String> registerRequest) {
        try {
            String username = registerRequest.get("username");
            String password = registerRequest.get("password");
            String realName = registerRequest.get("realName");
            String email = registerRequest.get("email");
            String phone = registerRequest.get("phone");

            if (username == null || password == null || realName == null) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "用户名、密码和真实姓名不能为空"
                ));
            }

            // 检查用户名是否已存在
            if (userService.existsByUsername(username)) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "用户名已存在"
                ));
            }

            // 创建新用户
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password); // 密码会在service中加密
            newUser.setRealName(realName);
            newUser.setEmail(email);
            newUser.setPhone(phone);
            newUser.setRole("END_USER"); // 默认角色
            newUser.setEnabled(true);
            newUser.setStatus("AVAILABLE");

            User savedUser = userService.saveUser(newUser);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "注册成功");
            response.put("user", Map.of(
                "id", savedUser.getId(),
                "username", savedUser.getUsername(),
                "realName", savedUser.getRealName(),
                "role", savedUser.getRole()
            ));

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "注册失败: " + e.getMessage()
            ));
        }
    }

    @GetMapping("/verify")
    public ResponseEntity<?> verifyToken(@RequestHeader("Authorization") String authHeader) {
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "无效的认证头"
                ));
            }

            String token = authHeader.substring(7);
            
            if (jwtUtil.validateToken(token)) {
                String username = jwtUtil.extractUsername(token);
                String role = jwtUtil.getRoleFromToken(token);
                
                User user = userService.findByUsername(username);
                if (user != null && user.getEnabled()) {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("message", "Token有效");
                    response.put("user", Map.of(
                        "id", user.getId(),
                        "username", user.getUsername(),
                        "realName", user.getRealName(),
                        "role", user.getRole(),
                        "departmentId", user.getDepartmentId()
                    ));
                    
                    return ResponseEntity.ok(response);
                } else {
                    return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "用户不存在或已被禁用"
                    ));
                }
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "Token无效或已过期"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "Token验证失败: " + e.getMessage()
            ));
        }
    }

    @PostMapping("/refresh")
    public ResponseEntity<?> refreshToken(@RequestHeader("Authorization") String authHeader) {
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "无效的认证头"
                ));
            }

            String token = authHeader.substring(7);
            
            if (jwtUtil.validateToken(token)) {
                String username = jwtUtil.extractUsername(token);
                String role = jwtUtil.getRoleFromToken(token);
                
                User user = userService.findByUsername(username);
                if (user != null && user.getEnabled()) {
                    // 生成新的token
                    String newToken = jwtUtil.generateToken(username, user.getRole());
                    
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", true);
                    response.put("message", "Token刷新成功");
                    response.put("token", newToken);
                    
                    return ResponseEntity.ok(response);
                } else {
                    return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "用户不存在或已被禁用"
                    ));
                }
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "原Token无效或已过期"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "Token刷新失败: " + e.getMessage()
            ));
        }
    }

    @PostMapping("/logout")
    public ResponseEntity<?> logout(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        try {
            logger.info("用户请求退出登录");
            
            // 这里可以添加token黑名单逻辑，如果需要的话
            // 目前JWT是无状态的，所以只需要客户端清除token即可
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "退出登录成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("退出登录处理异常: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "退出登录失败: " + e.getMessage()
            ));
        }
    }
} 